<template>
	<view class="layout">
		<uni-forms class="uni-forms" ref='form' :rules="rules" :model-value="addressInfo">
			<uni-forms-item label="收货人" name="name">
				<view class="line">
					<input type="text" v-model="addressInfo.name" placeholder="收货人姓名" />
				</view>
			</uni-forms-item>
			<uni-forms-item label="手机号码" name="phone">
				<view class="line">
					<input type="number" v-model="addressInfo.phone" placeholder="输入手机号" />
				</view>
			</uni-forms-item>
			<uni-forms-item label="所在地区" name="cityName">
				<view class="line picker">
					<picker mode="region"
						:value="[addressInfo.provinceName,addressInfo.cityName,addressInfo.districtName]"
						@change="onAddressChange">
						<view class="region" v-if="addressInfo.provinceName">
							{{addressInfo.provinceName + ' ' + addressInfo.cityName + ' ' + addressInfo.districtName }}
						</view>
						<view class="placeholder" v-else>
							请选择收货人所在地区
						</view>
					</picker>
					<view class="location" @click="onLocation">
						<uni-icons type="location" size="20"></uni-icons>定位
					</view>
				</view>
			</uni-forms-item>
			<uni-forms-item label="详细地址" name="address">
				<view class="line" style="border:1px solid rgba(193, 193, 193, 0.4);">
					<textarea style="height: 100rpx;" placeholder='输入详细地址' name="" id=""
						v-model="addressInfo.address"></textarea>
				</view>
			</uni-forms-item>
			<uni-forms-item label="设置默认地址" name="isDefault" :label-width="100">
				<view style="display: flex;align-items: center;flex-direction:row-reverse;">
					<switch :checked='addressInfo.isDefault' color="#ff0000" @change="switchChange" />
				</view>
			</uni-forms-item>
		</uni-forms>
		<button @click="submit">{{addressId? '更新':'新增'}}</button>
	</view>
</template>


<script setup>
	import { toast } from "@/utils/extendApi.js"
	import {
		reqAddAddress,
		reqAddressInfo,
		reqUpdateAddress
	} from '@/api/address.js'

	let addressInfo = reactive({
		name: '', // 收货人
		phone: '', // 手机号码
		provinceName: '', // 省
		provinceCode: '', // 省编码
		cityName: '', // 市
		cityCode: '', // 市编码
		districtName: '', // 区
		districtCode: '', // 市编码
		address: '', // 详细地址
		fullAddress: '', // 完整地址
		isDefault: false // 是否设置为默认地址，0 不设置为默认地址，1 设置为默认地址
	})
	let addressId = ref(null) // 有id为更新，无id为新增

	let form = ref()

	// 设置默认地址
	const switchChange = (e) => {
		addressInfo.isDefault = e.detail.value
	}

	// 选择地区
	const onAddressChange = (e) => {
		let addressArr = e.detail.value
		let addressCode = e.detail.code
		addressInfo.provinceName = addressArr[0]
		addressInfo.cityName = addressArr[1]
		addressInfo.districtName = addressArr[2]
		addressInfo.provinceCode = addressCode[0]
		addressInfo.cityCode = addressCode[1]
		addressInfo.districtCode = addressCode[2]
	}

	// 权限授权定位
	const onAuthorityLocation = async () => {
		// authSetting 获取小程序已经向用户申请的权限，并且会返回授权的结果
		// scope.userLocation：true 授权成功，false 授权失败，undefined 没有请求授权过
		let { authSetting } = await uni.getSetting()

		// 用户拒绝授权
		if (authSetting['scope.userLocation'] == false) {
			const modalRes = await uni.showModal({
				title: '授权提示',
				content: '需要获取地理位置信息，请确认授权'
			})

			if (modalRes.cancel) {
				toast({ title: '拒绝授权' })
				return;
			}

			// 打开小程序授权页面
			const { authSetting } = await uni.openSetting()

			// 用户设置允许授权
			if (authSetting['scope.userLocation']) {
				const locationRes = await uni.getLocation({})
				uni.chooseLocation({
					success: (res) => {
						res.address = addressInfo.address
					}
				})
			} else { // 用户设置拒绝授权
				toast({ title: '授权失败' })
			}
		} else { // 首次授权和授权成功
			try {
				const locationRes = await uni.getLocation({})
			} catch (e) {
				toast({ title: '您拒绝授权获取位置信息' })
			}
		}
	}

	// 打开高德地图定位
	const onLocation = async () => {
		try {
			// const locationRes = await uni.getLocation({}) 用户授权
			// 纬度，经度，地名
			let { latitude, longitude, name } = await uni.chooseLocation()
			uni.request({
				url: `https://restapi.amap.com/v3/geocode/regeo?location=${longitude},${latitude}`,
				method: 'GET',
				data: {
					output: 'json',
					key: '',
					radius: '1000',
					extensions: 'all'
				},
				success: (res) => {
					// 解构行政区编码、省、市、区
					let { adcode, province, city, district } = res.data.regeocode.addressComponent
					// 解构街道、门牌
					let { street, number } = res.data.regeocode.addressComponent.streetNumber
					// 解构标准地址
					let { formatted_address } = res.data.regeocode.formatted_address

					// 省编码，前2位有值，后4位是0
					addressInfo.provinceCode = adcode.replace(adcode.substring(2, 6), '0000')
					addressInfo.provinceName = province

					// 市编码，前4位有值，后2位是0
					addressInfo.cityCode = adcode.replace(adcode.substring(4, 6), '00')
					addressInfo.cityName = city

					// 区编码
					// 东菀市、中山市、儋州市、嘉峪关市，因其下无区县级；区编码就没有，区名就是市名
					addressInfo.districtCode = district.length == 0 ? '' : adcode
					addressInfo.districtName = district.length == 0 ? city : district

					// 详细地址
					addressInfo.address = street + number + name
					// 完整地址
					addressInfo.fullAddress = formatted_address + name
				}
			})
		} catch (e) {
			toast({ title: '您拒绝授权获取位置信息' })
		}
	}

	// 收货人姓名规则
	const valiName = (rule, value, data, callback) => {
		let regexp = /^[\u4e00-\u9fa5]{2,6}$/

		if (regexp.test(value)) {
			callback()
		} else {
			callback('请输入2-6个中文字符')
		}
	}

	// 手机号规则
	const valiPhone = (rule, value, data, callback) => {
		let regexp = /^1[3-9]\d{9}$/

		if (regexp.test(value)) {
			callback()
		} else {
			callback('请输入大陆手机号格式')
		}
	}

	// form规则
	let rules = ref({
		name: {
			rules: [

				{
					required: true,
					validateFunction: valiName,
					errorMessage: '请填写{label}',
				},
			],
			label: '姓名'
		},
		phone: {
			rules: [

				{
					required: true,
					validateFunction: valiPhone,
					errorMessage: '请填写手机号',
				}
			]
		},
		cityName: { rules: [{ required: true, errorMessage: '请填写省市区', }] },
		address: { rules: [{ required: true, errorMessage: '请填写详细地址', }] }
	})

	// 新增|更新，按钮
	const submit = () => {
		// 完整地址
		addressInfo.fullAddress = addressInfo.provinceName + addressInfo.cityName + addressInfo.districtName +
			addressInfo.address

		addressInfo.isDefault = addressInfo.isDefault ? 1 : 0

		form.value.validate().then(async () => {
			if (addressId.value) {
				let resule = await reqUpdateAddress(addressInfo)
				if (resule.code == 200) {
					uni.navigateBack()
					toast({ title: '更新成功' })
				}
			} else {
				let resule = await reqAddAddress(addressInfo)
				if (resule.code == 200) {
					uni.navigateBack()
					toast({ title: '新增成功' })
				}
			}
		}).catch(err => {
			toast({ title: '验证失败' })
		})
	}

	// 接收更新传过来的id，并根据id显示相应信息
	onLoad(async (options) => {
		let { id } = options
		if (id) {
			addressId.value = id
			let result = await reqAddressInfo(id)
			Object.assign(addressInfo, result.data)
		}

		uni.setNavigationBarTitle({
			title: `${id ? "更新" : "新增"}收货地址`
		})
	})

	onReady(() => {
		form.value.setRules(rules.value)
	})
</script>

<style lang="scss" scoped>
	.layout {
		width: 100vw;
		height: 100vh;
		padding: 16rpx;

		.line {
			width: 90%;
			height: 100%;
			display: flex;
			align-items: center;
			border-bottom: 1px solid rgba(193, 193, 193, 0.4);

			input {
				width: 90%;
				margin-left: 10rpx;
				padding-left: 8rpx;
			}
		}

		.picker {
			display: flex;
			justify-content: space-between;
			align-items: center;

			picker {
				width: 100%;

				.region {
					color: #333;
				}

				.placeholder {
					color: #969799;
				}
			}

			.location {
				width: 150rpx;
			}

		}

		button {
			background-color: rgba(250, 0, 4, 0.8);
			color: white;
			border-radius: 50rpx;
			width: 80%;
		}
	}
</style>